window.addEvent('domready', function() {
	chat.addExt({
		ini: function(){
			this.addNewCommand({
				r: 'newMsg'
				,fun: this.newMsg
				,answerFun: this.checkSendedMsg
			});
			this.addNewCommand({
				r: 'joinChat'
				,answerFun: this.checkJoing
			});
			this.addNewCommand({
				r: 'loginA'
				,answerFun: this.checkLoginA
			});
			
			this.textbox.addEvent('keydown', function(e){
				var msg = this.textbox.get("value");
				if(msg && e.key == 'enter'){
				
					//#Private element indicate the room where client is now.
					var p = $('private').get('text');
					if(p == 0)
						this.sendMsgTo(msg, 0);
					else
						this.sendMsgTo(msg, p);
				}
			}.bind(this));
			this.loginA();
			this.joinChat(this.idchat);
		}
		,putMsg: function(m){
			new Element('p', {
				text: m
			}).inject(this.publicChat, 'bottom');
		}
		,newMsg: function(command){
			this.putMsg(command.args.msg);
			return this.makeAnswer(command, {ok: true});
		}
		,sendMsgTo: function(msg, sala){
			this.makeAndSendCommand('newMsg', {'msg': msg, priv: sala} );
		}
		,checkSendedMsg: function(a){
			if(a.answer.ok === true)
				console.log("mensaje enviado correctamente.");
			else console.log("Mensaje no enviado correctamente");
			this.putMsg( this.commandPending[a.idc].args.msg );
		}
		
		,joinChat: function(){
			this.makeAndSendCommand('joinChat', {idchat : this.idchat} );
		}
		,checkJoing: function(a){
			if(a.answer.ok == true)
				console.log("Conectado al chat: "+this.idchat);
			else
				console.log("No se pudo conectar al chat.");
		}
		,loginA: function(nick, pass){
			this.makeAndSendCommand('loginA', {});
		}
		,checkLoginA: function(a){
			if(a.answer.ok === true){
				this.nick = a.answer.nick;
				this.putMsg("Conectado como: "+this.nick);
			} else {
				console.log("No se pudo conectar como anonimo.");
			}
		}
	});
});
